package com.jrx.anytxn.transaction.timer.job.queryRefundStatus.step;

import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.constant.BankCardConstant;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.feign.gateway.response.CoreResponse20;
import com.jrx.anytxn.feign.gateway.response.CoreResponse32;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.entity.TlRefundLog;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import com.jrx.anytxn.transaction.service.ISmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 溢缴款查询 - processor
 *
 * @author liuzb
 */
@Service
public class QueryRefundStatusProcessor implements ItemProcessor<TlRefundLog, TlRefundLog> {

    Logger logger = LoggerFactory.getLogger(QueryRefundStatusProcessor.class);
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IDealGatewayService dealGatewayService;
    @Lazy
    @Autowired
    private IInnerGatewayService innerGatewayService;
    @Autowired
    private ISmsService iSmsService;


    @Override
    public TlRefundLog process(TlRefundLog log) {

        TlRefundLog updateLog = new TlRefundLog();
        try {
            // D 待发起放款 从内部户到过渡户 后 从过渡户到用户卡号
            // PYMT001190（他行）+ACPG000090（本行）
            // 获取收款账户类型(0 = 本行二类户 1 = 本行借记卡 2 = 他行借记卡)
            ApiResponse<CoreResponse20> response = new ApiResponse<>();
            PrOrganizationTable organization = organizationTableService.findByOrId(log.getOrganizationId(), log.getTenantId());
            Date businessDate = organization.getNextProcessingDate();//机构上 当天日期

            updateLog.setId(log.getId());
            updateLog.setCustomerId(log.getCustomerId());
            updateLog.setTenantId(log.getTenantId());


            // 0.本行卡、1.他行卡
            String accountType = TransBizConstant.CARD_TYPE_0;
            if (!BankCardConstant.innerCardFlag(log.getToAcctNo())) {
                accountType = TransBizConstant.CARD_TYPE_1;
            }
            // 本行溢缴款查询
            if (Objects.equals(TransBizConstant.CARD_TYPE_0, accountType)) {
                String paymentRequest06Json = dealGatewayService.buildRefundReq(log);
                response = innerGatewayService.refund(paymentRequest06Json);
                logger.info("ACPG000090,用户：{}interestCompensate结果：{}", log.getCustomerId(), JSONObject.toJSONString(response));
                if (Objects.isNull(response) || Objects.isNull(response.getData())
                        || TransBizConstant.GATEWAY_SUC != response.getCode() || response.getData().getBusMsg().contains(TransBizConstant.GATEWAY_CONTENT_TIMEOUT)) {
                    logger.warn("调用溢缴款查询接口出现异常:{}", JSONObject.toJSONString(response));
                    updateLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_O);
                    updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), businessDate));
                    return updateLog;
                }
            } else {
                // 他行卡溢缴款查询
                TlDisbursementLog disLog = new TlDisbursementLog();
                disLog.setRefNo(log.getRefNo());
                disLog.setTenantId(log.getTenantId());
                String coreRequest32Json = dealGatewayService.buildOuterDisbursementReq(disLog);
                ApiResponse<CoreResponse32> coreResponse32 = innerGatewayService.pcpTransactionStatus(coreRequest32Json);
                logger.info("PYMT000700,用户：{},溢缴款结果：{}", log.getCustomerId(), JSONObject.toJSONString(response));
                if (Objects.isNull(coreResponse32) || Objects.isNull(coreResponse32.getData())
                        || TransBizConstant.GATEWAY_SUC != coreResponse32.getCode() || coreResponse32.getData().getBusMsg().contains(TransBizConstant.GATEWAY_CONTENT_TIMEOUT)) {
                    logger.warn("调用溢缴款查询接口出现异常:{}", JSONObject.toJSONString(coreResponse32));
                    updateLog.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_O);
                    updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), businessDate));
                    return updateLog;
                }
                CoreResponse20 res = new CoreResponse20();
                CoreResponse32 data = coreResponse32.getData();
                BeanUtils.copyProperties(data, res);
                String dealState = data.getDealState();
                res.setDealResult(dealState);
                res.setPcpId(data.getPcpId());
                res.setSysCode(data.getSysCd());
                res.setTransactionId25(data.getCbsFTId());
                res.setDealState(dealState);
                res.setBusCode(data.getBusCode());
                res.setBusMsg(data.getBusMsg());
                updateLog.setSumStatus(dealState);
                response.setData(res);
            }
            logger.info("response:{}", JSONObject.toJSONString(response));
            CoreResponse20 res = response.getData();
            String result = res.getDealState();
            updateLog.setReturnCode(res.getBusCode());
            updateLog.setReturnMsg(res.getBusMsg());
            updateLog.setReturnStatus(result);
            updateLog.setSumStatus(result);
            updateLog.setCompleteTime(DateUtils.getBusinessTime(new Date(), businessDate));
            //添加短信逻辑 只有拿到终态才需要处理
            if (TransBizConstant.PAYMENT_LOG_SUM_STATUS_S.equals(updateLog.getSumStatus())) {
                log.setSumStatus(TransBizConstant.PAYMENT_LOG_SUM_STATUS_S);
                try {
                    iSmsService.refundSmsProcess(log);
                } catch (Exception e) {
                    logger.error("短信发送异常", e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("QueryRefundStatusProcessor发生异常：{}", e);
        }
        return updateLog;
    }

}
